package com.jming.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jming.yygh.cmn.listener.DictListener;
import com.jming.yygh.cmn.mapper.DictMapper;
import com.jming.yygh.cmn.service.DictService;
import com.jming.yygh.model.cmn.Dict;
import com.jming.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author jming
 * @date 2021-04-17
 */
@Service
public class DictServiceImpl
        extends ServiceImpl<DictMapper, Dict>
        implements DictService {

    @Override
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {

        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        // 将查询的结果保存到集合中
        List<Dict> dictsList = baseMapper.selectList(wrapper);

        // 遍历集合设置每个dict对象的hasChildren
        for (Dict dict : dictsList) {
            long dictId = dict.getId();
            QueryWrapper<Dict> wrapperChildren = new QueryWrapper<>();
            wrapperChildren.eq("parent_id", dictId);
            if (baseMapper.selectCount(wrapperChildren) > 0) {
                dict.setHasChildren(true);
            } else {
                dict.setHasChildren(false);
            }
        }
        return dictsList;
    }

    @Override
    public void exportDataDict(HttpServletResponse response) {

        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String filename = "dict";
        response.setHeader("Content-disposition", "attachment:filename" + filename + ".xls");

        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);

        // 封装数据
        List<DictEeVo> dictEeVos = new ArrayList<>();
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVos.add(dictEeVo);
        }

        // 调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictEeVos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {

        // 若果dictCode为空，直接按value查询
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        } else {
            // 如果不为空 则根据dictCode和value查询
            // 根据dictCode查询dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            long parentId = codeDict.getId();

            // 根据parentId和value进行查询
            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parentId)
                    .eq("value", value));

            // 返回数据
            return finalDict.getName();
        }
    }

    @Override
    public List<Dict> fingByDictCode(String dictCode) {

        // 根据dictCode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);

        // 根据id获取子节点
        List<Dict> chlidData = this.findChlidData(dict.getId());

        return chlidData;
    }

    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }
}
